/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.psp.service.impl;

import io.swagger.models.auth.In;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.cspimp.psp.domain.Chemicla;
import me.zhengjie.modules.cspimp.psp.domain.ChemiclaStockOut;
import me.zhengjie.modules.cspimp.psp.repository.ChemiclaRepository;
import me.zhengjie.modules.cspimp.psp.service.dto.ChemiclaStockInDto;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.psp.repository.ChemiclaStockOutRepository;
import me.zhengjie.modules.cspimp.psp.service.ChemiclaStockOutService;
import me.zhengjie.modules.cspimp.psp.service.dto.ChemiclaStockOutDto;
import me.zhengjie.modules.cspimp.psp.service.dto.ChemiclaStockOutQueryCriteria;
import me.zhengjie.modules.cspimp.psp.service.mapstruct.ChemiclaStockOutMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-30
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ChemiclaStockOutServiceImpl implements ChemiclaStockOutService {

    private final ChemiclaStockOutRepository chemiclaStockOutRepository;
    private final ChemiclaStockOutMapper chemiclaStockOutMapper;
    private final ChemiclaRepository chemiclaRepository;
    private final UserRepository userRepository;

    @Override
    public Map<String, Object> queryAll(ChemiclaStockOutQueryCriteria criteria, Pageable pageable) {
        List<ChemiclaStockOut> page = chemiclaStockOutRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<ChemiclaStockOutDto> chemiclaStockOutList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page)) {
            for (ChemiclaStockOut chemiclaStockOut : page) {
                ChemiclaStockOutDto chemiclaStockOutDto = new ChemiclaStockOutDto();
                BeanUtils.copyProperties(chemiclaStockOut, chemiclaStockOutDto);
                User user = userRepository.findById(chemiclaStockOut.getAuditId()).get();
                if (null != user) {
                    chemiclaStockOutDto.setUsername(user.getUsername());
                }
                chemiclaStockOutList.add(chemiclaStockOutDto);
            }
        }
        return PageUtil.toPage(PageUtil.listPage(chemiclaStockOutList, pageable));
    }

    @Override
    public List<ChemiclaStockOutDto> queryAll(ChemiclaStockOutQueryCriteria criteria) {
        return chemiclaStockOutMapper.toDto(chemiclaStockOutRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public ChemiclaStockOutDto findById(Long id) {
        ChemiclaStockOut chemiclaStockOut = chemiclaStockOutRepository.findById(id).orElseGet(ChemiclaStockOut::new);
        ValidationUtil.isNull(chemiclaStockOut.getId(), "ChemiclaStockOut", "id", id);
        User user = userRepository.findById(chemiclaStockOut.getAuditId()).get();
        ChemiclaStockOutDto chemiclaStockOutDto = new ChemiclaStockOutDto();
        BeanUtils.copyProperties(chemiclaStockOut, chemiclaStockOutDto);
        if (null != user) {
            chemiclaStockOutDto.setUsername(user.getUsername());
        }
        return chemiclaStockOutDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChemiclaStockOutDto create(ChemiclaStockOut resources) {
        Chemicla chemicla = chemiclaRepository.findById(resources.getChemiclaId()).get();
        Integer stockCount = chemicla.getStockCount();
        Integer stockOutCount = resources.getStockOutCount();
        Integer currentStockCount = resources.getCurrentStockCount();
        if (currentStockCount < stockOutCount) {
            throw new BadRequestException("当前库存量小于出库量，不能出库");
        }
        chemicla.setStockCount((stockCount - stockOutCount));
        chemiclaRepository.save(chemicla);
        resources.setCid(0l);
        return chemiclaStockOutMapper.toDto(chemiclaStockOutRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ChemiclaStockOut resources) {
        ChemiclaStockOut chemiclaStockOut = chemiclaStockOutRepository.findById(resources.getId()).orElseGet(ChemiclaStockOut::new);
        ValidationUtil.isNull(chemiclaStockOut.getId(), "ChemiclaStockOut", "id", resources.getId());
        chemiclaStockOut.copy(resources);
        chemiclaStockOutRepository.save(chemiclaStockOut);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            chemiclaStockOutRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ChemiclaStockOutDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ChemiclaStockOutDto chemiclaStockOut : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建者", chemiclaStockOut.getCreateBy());
            map.put("更新者", chemiclaStockOut.getUpdateBy());
            map.put("创建日期", chemiclaStockOut.getCreateTime());
            map.put("更新时间", chemiclaStockOut.getUpdateTime());
            map.put("出库量", chemiclaStockOut.getStockOutCount());
            map.put("审核人", chemiclaStockOut.getAuditId());
            map.put("化学品id", chemiclaStockOut.getChemiclaId());
            map.put("当前库存量", chemiclaStockOut.getCurrentStockCount());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}